﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilZ.Dotnet.Ex.Communication.Net.BMQ
{
    /// <summary>
    /// BMQ文本消息
    /// </summary>
    public class BMQTextMessage : BMQDataMessageAbs
    {

        private string _text;
        /// <summary>
        /// 文本内容
        /// </summary>
        public string Text
        {
            get { return _text; }
        }


        /// <summary>
        /// 构造函数-解析
        /// </summary>
        public BMQTextMessage()
            : base(BMQMessageTypes.TextMessage)
        {

        }


        /// <summary>
        /// 构造函数-创建
        /// </summary>
        /// <param name="topic">订阅主题</param>
        /// <param name="text">文本内容</param>
        public BMQTextMessage(short topic, string text)
            : base(BMQMessageTypes.TextMessage, topic)
        {
            this._text = text;
        }



        /// <summary>
        /// 获取消息大小
        /// </summary>
        /// <returns>消息大小</returns>
        protected override int GetMessageSize()
        {
            if (string.IsNullOrEmpty(this._text))
            {
                return BMQ_DATA_HEADER_SIZE;
            }

            return BMQ_DATA_HEADER_SIZE + Encoding.UTF8.GetByteCount(this._text);
        }


        /// <summary>
        /// 获取内容二进制数据
        /// </summary>
        /// <returns></returns>
        protected override byte[] GetContentBytes()
        {
            if (this._text == null)
            {
                return new byte[0];
            }
            else
            {
                return Encoding.UTF8.GetBytes(this._text);
            }
        }

        /// <summary>
        /// 设置内容二进制数据
        /// </summary>
        /// <param name="data">内容二进制数据</param>
        protected override void SetContentBytes(byte[] data)
        {
            this._text = Encoding.UTF8.GetString(data);
        }

    }
}
